package org.fight.landowner.remoting.netty;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
import org.fight.landowner.remoting.protocol.RemotingCommand;
import org.fight.landowner.remoting.protocol.RemotingSerializableUtil;

import java.nio.ByteBuffer;

/**
 * @Author wangxuehao02
 * @Date 2024/2/3 12:54 AM
 * @Description
 **/

@ChannelHandler.Sharable
public class NettyEncoder extends MessageToByteEncoder<RemotingCommand> {

    private static NettyEncoder nettyEncoder = null;

    @Override
    protected void encode(ChannelHandlerContext channelHandlerContext, RemotingCommand remotingCommand, ByteBuf byteBuf) throws Exception {
        ByteBuffer byteBuffer = RemotingSerializableUtil.serialize(remotingCommand);

        // todo 这样写正确吗，还是需要写到 channel
        byteBuf.writeBytes(byteBuffer);
    }

    public static NettyEncoder getInstance() {
        if (NettyEncoder.nettyEncoder == null) {
            synchronized (NettyEncoder.class) {
                if (NettyEncoder.nettyEncoder == null) {
                    NettyEncoder.nettyEncoder = new NettyEncoder();
                }
            }
        }
        return NettyEncoder.nettyEncoder;
    }
}
